package zy.wq.config;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.http.HttpMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.HttpMediaTypeNotAcceptableException;

public class HttpOutputMessageWriter {

	private HttpMessageConverters messageConverters;
	
	private MediaType defaultResponseMeidaType = MediaType.APPLICATION_JSON_UTF8;
	
	@SuppressWarnings({ "unchecked", "resource" })
	public void write(HttpServletRequest request,
			HttpServletResponse response, Object data)
			throws IOException, ServletException {
		response.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
		HttpMessage httpMessage = new ServletServerHttpRequest(request);
		HttpOutputMessage responseMessage = new ServletServerHttpResponse(response);
		List<MediaType> accepts = new ArrayList<MediaType>(httpMessage.getHeaders().getAccept());
		if(accepts.isEmpty() ) {
			accepts.add(defaultResponseMeidaType);
		}
		for(MediaType accept : accepts) {
			for(@SuppressWarnings("rawtypes") HttpMessageConverter c : messageConverters.getConverters()) {
				if(c.canWrite(data.getClass(), accept)) {
					c.write(data, accept, responseMessage);
					return;
				}
			}
		}
		throw new HttpMediaTypeNotAcceptableException(accepts);
	}
	


	public HttpMessageConverters getMessageConverters() {
		return messageConverters;
	}

	public void setMessageConverters(HttpMessageConverters messageConverters) {
		this.messageConverters = messageConverters;
	}

	public MediaType getDefaultResponseMeidaType() {
		return defaultResponseMeidaType;
	}

	public void setDefaultResponseMeidaType(MediaType defaultResponseMeidaType) {
		this.defaultResponseMeidaType = defaultResponseMeidaType;
	}


	
	

}
